<?php


namespace PKApp\Poster;

use PKApp\Poster\Classes\ImageService;
use PKApp\Poster\Classes\TextService;
use PKApp\Poster\Classes\TraitPoster;
use PKCommon\Controller\AdminController;
use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\Numbers;

class AdminSetSpace extends AdminController
{
    use TraitPoster;

    public function Main()
    {
        $this->callOfSellFunc();
    }

    protected function model(): array
    {
        $post = $this->checkModel(['id', 'name', 'posterType']);
        $post['name'] = $this->checkPostFieldIsEmpty('name', 'poster_NameEmpty');
        $post['posterType'] = $this->checkPostFieldIsEmpty('posterType', 'poster_TypeEmpty');
        $PosterTypeList = dict('PosterType');
        array_key_exists($post['posterType'], $PosterTypeList) ?: $this->noticeByJson('poster_TypeEmpty');
        return $post;
    }

    protected function apiByCreate()
    {
        $post = $this->model();
        unset($post['id']);
        $post['createTime'] = time();
        $this->serviceOfPoster()->Add($post);
        $this->inputSuccess();
    }

    protected function apiByChange()
    {
        $post = $this->model();
        Numbers::IsId($post['id']) ?: $this->noticeByPage('posterIdEmpty');
        $this->serviceOfPoster()->UpdateById($post['id'], $post);
        $this->inputSuccess();
    }

    protected function apiByDel()
    {
        $id = request()->post('id');
        Numbers::IsId($id) ?: $this->noticeByPage('posterIdEmpty');
        $entity_space = $this->service->interface_getEntityById($id);
        $params_dbQuery = ['posterId' => $id,];
        switch (Arrays::GetKey('posterType', $entity_space)) {
            case 'text':
                $service_text = new TextService();
                $list = $service_text->GetList($params_dbQuery);
                empty($list) ?: $this->noticeByJson('poster_DelError');
                break;
            case 'image':
                $service_img = new ImageService();
                $list = $service_img->GetList($params_dbQuery);
                empty($list) ?: $this->noticeByJson('poster_DelError');
                break;
            default:
                $this->noticeByJson('poster_TypeError');
                break;
        }
        $this->serviceOfPoster()->DeleteById($id);
        $this->inputSuccess();
    }

    protected function removeCache()
    {
        cache()->Tmp()->RemoveDir(dict('cache_dir'));
        $this->json();
    }
}